export const socket = socketio => {

  var UUIDMap = {};
  socketio.on('connection', function (socket) {
    console.info('connection:', socket.id);
    var UUID;
    //客户端进行uuid与socket.id绑定
    socket.on('register', function (data) {
      var regUUID = data['uuid'];
      //如果存在 解决刷新二维码造成的uuid不一致问题
      if (UUID != null) {
        delete UUIDMap[UUID];
      }
      UUID = regUUID;
      UUIDMap[UUID] = socket.id;
      console.info('save in UUIDMap', UUID);
    });

    //手机端确认登陆
    socket.on('confirm', function (data) {
      //提示web端 手机端扫码成功 并将token令牌返回
      replayToDisplayer(data, 'result');
      //同时提示手机端 验证成功
      socket.emit('success', { result: 'success' })
      console.info('mobile comfrim submit');
    });

    //客户端断开链接
    socket.on('disconnect', function () {
      console.info('disconnect', socket.id);
      if (UUID != null) {
        console.info('delete ', UUID);
        delete UUIDMap[UUID];
      }
    });
  });

  /**
   * 向指定web端发送信息
   * 
   * @param {json} data 要返回的数据
   * @param {string} event 要回调客户端的监听事件
   * @returns {undefined}
   */
  function replayToDisplayer(data, event) {
    var submitUUID = data['uuid'];
    var displayerSocket = findSocketByUUID(submitUUID);

    if (displayerSocket != null) {
      console.info('find socket and emit back ', submitUUID);
      displayerSocket.emit(event, data);
    }
  }

  /**
   * 通过uuid查找socket connection id
   * 
   * @param {uuid} data 要返回的数据
   */
  function findSocketByUUID(UUID) {
    var targetSocketID = UUIDMap[UUID];
    if (targetSocketID != null) {
      var targetSocket = socketio.sockets.connected[targetSocketID];
      if (targetSocket != null) {
        return targetSocket;
      } else {
        console.info('cant find target socket by uuid: ', UUID);
      }
    } else {
      console.error('cant find target socket id by uuid: ', UUID);
    }
    return null;
  }

}

